﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Net.NetworkInformation;
using Microsoft.Phone.Tasks;
using MiruPublic;

namespace MangaKurosagi
{
    using Microsoft.Phone.Shell;
    using System.ComponentModel;

    public partial class MainPage : PhoneApplicationPage
    {
        Popup popup = new Popup();
        ApplicationBarController appbar;
        
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            InintializeControls();

            ControlManager.ShowLoading(popup, "Đang tải các tập truyện mới nhất...", true);

            if (NetworkInterface.GetIsNetworkAvailable() == true)
            {
                Global.PageNewCurrent = 1;

                LoadListNew(Global.PageNewCurrent);

                Global.PageAllCurrent = 1;

                LoadAllStories(Global.PageAllCurrent);
            }
            else
            {
                MessageBox.Show("Không thể kết nối mạng \n Kiểm tra wifi/cellular và truy cập lại để tải truyện");

                popup.IsOpen = false;
            }
        }
        private void InintializeControls()
        {
            this.appbar = new ApplicationBarController(this.ApplicationBar);

             //prepare all Icon Buttons and Menu Items
            this.appbar.AddNewButton("Đầu tiên", "/icons/appbar.transport.rew.rest.png", true, ApplicationBarIconButton_Click);
            this.appbar.AddNewButton("Trước", "/icons/appbar.back.rest.png", true, ApplicationBarIconButton_Click);
            this.appbar.AddNewButton("Tiếp", "/icons/appbar.next.rest.png", true, ApplicationBarIconButton_Click);
            this.appbar.AddNewButton("Cuối", "/icons/appbar.transport.ff.rest.png", true, ApplicationBarIconButton_Click);
            this.appbar.AddNewMenuItem("Tìm kiếm truyện", true, ApplicationBarMenuItem_Click);
            this.appbar.AddNewMenuItem("Đánh giá sản phẩm", true, ApplicationBarRateMenuItem_Click);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NetworkInterface.GetIsNetworkAvailable() == true)
            {
                listUnfinish.ItemsSource = null;

                listUnfinish.ItemsSource = Global.ListChapUnFinish;

                listFavious.ItemsSource = null;

                listFavious.ItemsSource = StoriesFarvious.ConvertTo(Global.ListStoriesLike);
            }
        }
       
        private void LoadListNew(int PageIndex)
        {
            LeadBlogtruyen client = new LeadBlogtruyen();

            client.leadAll = false;

            string Url = "http://m.blogtruyen.com/trangchu/?page="+PageIndex.ToString();

            client.DownLoadURL(Url);

            client.ListUpdateSucess += (s, args) =>
            {
                ListManga.ItemsSource = null;

                ListManga.ItemsSource = args.listResult;

                Global.PageNewMax = args.PageCount;

                popup.IsOpen = false;
            };
        }

        private void LoadAllStories(int PageIndex)
        {
            LeadBlogtruyen client = new LeadBlogtruyen();

            client.leadAll = true;

            string Url = "http://m.blogtruyen.com/danhsach/?page=" + PageIndex.ToString();

            client.DownLoadURL(Url);

            client.ListAllStoriesUpdateSucess += (s, args) =>
            {
                ListAll.ItemsSource = null;

                ListAll.ItemsSource = args.listResult;

                Global.PageAllMax = args.PageCount;
            };
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult Result = MessageBox.Show("Bạn chắc chắn thoát chứ?", "thoát ứng dụng", MessageBoxButton.OKCancel);

            if (Result == MessageBoxResult.Cancel)

                e.Cancel = true;
            else
            {
                if (NavigationService.CanGoBack)
                {
                    while (NavigationService.RemoveBackEntry() != null)
                    {
                        NavigationService.RemoveBackEntry();
                    }
                }
            }
        }
        
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            string header = (sender as MenuItem).Header.ToString();

            ListBoxItem chap = this.listUnfinish.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            ChapUnfinish item = chap.Content as ChapUnfinish;
            if (chap != null)
            {
                var Result = MessageBox.Show("Bạn muốn xóa " + item.Title.ToString(), "Xóa truyện", MessageBoxButton.OKCancel);

                if (Result == MessageBoxResult.OK)
                {
                    Global.ListChapUnFinish.Remove(item);
                    listUnfinish.ItemsSource = null;
                    listUnfinish.ItemsSource = Global.ListChapUnFinish;
                    StorageHelper.SaveUnfinishXML("ChapUnfinish.xml", Global.ListChapUnFinish);
                }
                return;
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            string header = (sender as MenuItem).Header.ToString();

            ListBoxItem chap = this.listFavious.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            if (chap != null)
            {
                StoriesFarvious item = chap.Content as StoriesFarvious;

                var Result = MessageBox.Show("Bạn muốn xóa " + item.Title.ToString(), "Xóa truyện", MessageBoxButton.OKCancel);

                if (Result == MessageBoxResult.OK)
                {
                    var selected = Global.ListStoriesLike.Where(s => s.Title == item.Title && s.Url == item.Url).First();
                    Global.ListStoriesLike.Remove(selected);
                    listFavious.ItemsSource = null;
                    listFavious.ItemsSource = StoriesFarvious.ConvertTo(Global.ListStoriesLike);
                    StorageHelper.SaveFarviousXML("StoriesFarvious.xml", Global.ListStoriesLike);
                }
                return;
            }
        }

        private void ListManga_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ItemDetails item = ListManga.SelectedItem as ItemDetails;

            if (item == null) return;

            Global.StoriesSelected = Stories.Convert(item);
            Global.StoriesSelected.Update = true;
            NavigationService.Navigate(new Uri("/ViewDetails.xaml?", UriKind.Relative));
        }

        private void ListAll_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Chap item = ListAll.SelectedItem as Chap;
            if (item == null) return;
            Stories stori = new Stories() { Title=item.Title,Url=item.Url};
            Global.StoriesSelected = stori;
            Global.StoriesSelected.Update = true;
            NavigationService.Navigate(new Uri("/ViewDetails.xaml?", UriKind.Relative));
        }

        private void listUnfinish_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ChapUnfinish chap = listUnfinish.SelectedItem as ChapUnfinish;

            if (chap == null) return;

            Global.ChapSelected = new Chap() { Url = chap.Url, Title = chap.Title, Update = true };
            Global.StoriesSelected = chap.root;

            NavigationService.Navigate(new Uri("/ReadChap.xaml", UriKind.Relative));
        }

        private void listFavious_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            StoriesFarvious item = listFavious.SelectedItem as StoriesFarvious;

            if (item == null) return;

            Global.StoriesSelected = StoriesFarvious.Convert(item);
            Global.StoriesSelected.Update = true;
            NavigationService.Navigate(new Uri("/ViewDetails.xaml?", UriKind.Relative));
        }

        private void pivot1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = MainPivot.SelectedIndex;

            this.appbar.ShowAppBar(false);

            switch (i)
            {
                case 0: // dashboard
                    this.appbar.ShowAppBar(true);
                    this.appbar.ShowButtons(new string[] { "Đầu tiên", "Trước", "Tiếp","Cuối" });
                    this.appbar.RemoveMenuItems("Tìm kiếm truyện");
                    this.appbar.ShowMenuItem("Đánh giá sản phẩm");
                    break;
                case 1: // dashboard
                    this.appbar.ShowAppBar(true);
                    this.appbar.ShowButtons(new string[] { "Đầu tiên", "Trước", "Tiếp", "Cuối" });
                    this.appbar.ShowMenuItems(new string[] { "Tìm kiếm truyện", "Đánh giá sản phẩm" });
                    break;
            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            int i = MainPivot.SelectedIndex;
            ApplicationBarIconButton btn = (ApplicationBarIconButton)sender;
            string text = btn.Text.ToLower();

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            { 
                MessageBox.Show("Không thể kết nối mạng \n Kiểm tra wifi/cellular và truy cập lại để tải truyện");

                return;
            }
           
            if (text == "đầu tiên" && i == 0)
            {
                Global.PageNewCurrent=1;

                LoadListNew(Global.PageNewCurrent);
            }
            if (text == "đầu tiên" && i == 1)
            {
                Global.PageAllCurrent = 1;

                LoadAllStories(Global.PageAllCurrent);
            }
            if (text == "trước" && i == 0)
            {
                if (Global.PageNewCurrent > 1)
                {
                    Global.PageNewCurrent-- ;

                    LoadListNew(Global.PageNewCurrent);
                }
            }
            if (text == "trước" && i == 1)
            {
                if (Global.PageAllCurrent > 1)
                {
                    Global.PageAllCurrent--;

                    LoadAllStories(Global.PageAllCurrent);
                }
            }
            if (text == "tiếp" && i==0)
            {
                if (Global.PageNewCurrent < Global.PageNewMax)
                {
                    Global.PageNewCurrent++;

                    LoadListNew(Global.PageNewCurrent);
                }
            }
            if (text == "tiếp" && i == 1)
            {
                if (Global.PageAllCurrent < Global.PageAllMax)
                {
                    Global.PageAllCurrent++;

                    LoadAllStories(Global.PageAllCurrent);
                }
            }
            if (text == "cuối" && i == 0)
            {
                Global.PageNewCurrent = Global.PageNewMax;
                LoadListNew(Global.PageNewCurrent);
            }
            if (text == "cuối" && i == 1)
            {
                Global.PageAllCurrent = Global.PageAllMax;
                LoadAllStories(Global.PageAllCurrent);
            }
            //else if (text == "save")
            //{
            //    this.Names.Add(txName.Text);
            //    this.appbar.ShowButtons("add");

            //    panelAdd.Visibility = System.Windows.Visibility.Collapsed;
            //    lbNames.Visibility = System.Windows.Visibility.Visible;
            //}
            //else if (text == "cancel")
            //{
            //    panelAdd.Visibility = System.Windows.Visibility.Collapsed;
            //    lbNames.Visibility = System.Windows.Visibility.Visible;
            //    this.appbar.ShowButtons("add");
            //}
            //else if (text == "delete")
            //{
            //    this.Names.Remove(lbNames.SelectedItem.ToString());
            //}
            //else if (text == "clear")
            //{
            //    this.Names.Clear();
            //    this.appbar.ShowButtons("add");
            //}
            //else if (text == "add menu")
            //{
            //    menucount++;
            //    string menuname = "Menu Item " + menucount;
            //    this.appbar.AddNewMenuItem(menuname, true, ApplicationBarMenuItem_Click);
            //    this.appbar.ShowMenuItem(menuname);
            //}
            //else if (text == "clear menus")
            //{
            //    this.appbar.RemoveMenuItems();
            //}
        }

        private void SearchStories(string keyword)
        {
            Website client = new Website();

            string Url = "http://m.blogtruyen.com/timkiem/?truyen=" + HttpUtility.UrlEncode(keyword);

            client.DownLoadURL(Url);

            client.DownLoadCompleted += (s, args) =>
            {
                LoadListSearch(Utils.GetStringBetweenText(args.Result, "<!-- quảng cáo -->", "<br />"));
            };
        }
        void LoadListSearch(string content)
        {
            string CheckContent = content;

            string line = "";

            line = Utils.GetStringBetweenText(CheckContent, "<a href=", "</a>");

            if (line == "")
            {
                MessageBox.Show("Không tìm thấy kết quả nào");

                return;
            }

            List<Chap> lsResult = new List<Chap>();

            while (line != "")
            {
                string Title = Utils.strip_tags(Utils.GetStringBetweenText(line, "\">", ""));

                string Url = "http://m.blogtruyen.com" + Utils.GetStringBetweenText(line, "\"", "\"");
                Chap storie = new Chap() {Title=Title,Url=Url };

                lsResult.Add(storie);

                CheckContent = Utils.GetStringBetweenText(CheckContent, line, "");

                line = Utils.GetStringBetweenText(CheckContent, "<a href=", "</a>");
            }
            ListAll.ItemsSource = null;

            ListAll.ItemsSource = lsResult;
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            Popup popup = new Popup();
            InputControls control = new InputControls();
            popup.Child = control;
            popup.IsOpen = true;
            control.background.Tap += (s, args) =>
            {
                popup.IsOpen = false;
            };
            control.btnSearch.Click += (s, args) =>
            {
                popup.IsOpen = false;

                SearchStories(control.txtKeyword.Text);
            };

            control.btnCancel.Click += (s, args) =>
            {
                popup.IsOpen = false;
            };
            control.txtKeyword.GotFocus += (s, args) =>
            {
                control.txtKeyword.Text = "";
            };
        }
        private void ApplicationBarRateMenuItem_Click(object sender, EventArgs e)
        {
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();

            marketplaceReviewTask.Show();
        }
    }
}